package com.voxel.sense.infomsg.utils;



import android.content.Context;
import android.text.TextUtils;
import android.util.TypedValue;

public class ResourceUtil {
	public static String getString(Context context, String name) {
		int id = getStringIdByName(context, name);
		return context.getResources().getString(id);
	}

	public static String getStringByResName(Context context, String name) {
		if (TextUtils.isEmpty(name)) {
			throw new RuntimeException("string name is empty");
		}
		return context.getResources().getString(
				getStringIdByName(context, name));
	}

	public static int getStringIdByName(Context context, String name) {
		if (TextUtils.isEmpty(name)) {
			throw new RuntimeException("string name is empty");
		}
		return context.getResources().getIdentifier(name, "string",
				context.getPackageName());
	}

	public static int getDrawableIdByName(Context context, String name) {
		if (TextUtils.isEmpty(name)) {
			throw new RuntimeException("string name is empty");
		}
		return context.getResources().getIdentifier(name, "drawable",
				context.getPackageName());
	}

	public static int getMipmapIdByName(Context context, String name) {
		if (TextUtils.isEmpty(name)) {
			throw new RuntimeException("string name is empty");
		}

		return context.getResources().getIdentifier(name, "mipmap",
				context.getPackageName());
	}
	public static int getColorIdByName(Context context, String name) {
		if (TextUtils.isEmpty(name)) {
			throw new RuntimeException("string name is empty");
		}
		return context.getResources().getIdentifier(name, "color",
				context.getPackageName());
	}
	//返回的是px 这是向下取整的 如果density = 0.75时，1dp返回的是0,而3dp返回的是2。5dp返回的是3。
	public static int getDimensionPixelOffset(Context context, int id) {
		return context.getResources().getDimensionPixelOffset(id);
	}
	//返回的是px 最少都是1，当大于1时，采取四舍五入，如果density = 0.75时，0.1dp返回的是仍然是1。而3dp返回的是2
	public static int getDimenPixelSize(Context context, int id) {
		return context.getResources().getDimensionPixelSize(id);
	}
	//返回的是px 如果density = 0.75时，0.1dp返回的是0.075
	public static float getDimension(Context context, int id) {
		return context.getResources().getDimension(id);
	}
	//无论16sp,16dp,16px,16in 都是返回16
	//当是16sp时，value.data=4098，1000000000010(b),f=16.0
	//当是16dp时,value.data=4097,1000000000001(b),f=16.0
	//当是16px时,value.data:4096,1000000000000(b),f=16.0
	//当是16.2dp时,value.data=135895329,1000000110011001100100100001(b),f=16.199982
	//dimension在系统中大概是以数值+单位的形式存储的。,16sp,16dp,16px高位是相同的，低位字节不一样
	//http://johnsonxu.iteye.com/blog/1929027
	public static int getDimensionNumber(Context context, int id) {
		TypedValue value = new TypedValue();
		context.getResources().getValue(id, value, true);
		float f = TypedValue.complexToFloat(value.data);
		return (int) f;
	}
	public static String getResourceName(Context context, int resId) {
		return context.getResources().getResourceName(resId);
	}

}
